"use strict";

/**
 * 日志记录
 */
const log4js = require('log4js');
const globalConfig = require('../../config/global_config');

const log_dir = globalConfig.log_dir;

//错误日志目录
// const errorPath = "/error";
//错误日志文件名
const errorFileName = "error";
//错误日志输出完整路径
const errorLogPath = log_dir + errorFileName;

//响应日志目录
// const responsePath = "/info";
//响应日志文件名
const responseFileName = "info";
//响应日志输出完整路径
const responseLogPath = log_dir + responseFileName;

const log_config = {
    appenders: {
        debug: {
            type: 'console'
        },
        info: {
            type: 'dateFile',
            filename: responseLogPath,
            alwaysIncludePattern: true,
            pattern: "-yyyyMMdd-hh.log"
        },
        error: {
            type: 'dateFile',
            filename: errorLogPath,
            alwaysIncludePattern: true,
            pattern: "-yyyyMMdd-hh.log"
        },
    },
    categories: {
        info: {
            // appenders: ['debug', 'info'],  // 不需要控制台显示就去掉'debug'项
            appenders: ['info'],  // 不需要控制台显示就去掉'debug'项
            level: 'info'
        },
        error: {
            appenders: ['error'],
            level: 'error'
        },
        default: {
            appenders: ['debug', 'info'],
            level: 'trace'
        }
    }
};
log4js.configure(log_config);

let logUtil = {};
const infoLogger = log4js.getLogger('info');
const errorLogger = log4js.getLogger('error');

logUtil.logInfo = function (str) {
    if (str) {
        infoLogger.info(str);
    }
};

logUtil.logError = function (str) {
    if (str) {
        errorLogger.error(str);
    }
};

//封装错误日志
logUtil.logException = function (ctx, error, resTime) {
    if (ctx && error) {
        logUtil.logError(formatError(ctx, error, resTime));
    }
};

//封装响应日志
logUtil.logResponse = function (ctx, resTime) {
    if (ctx) {
        logUtil.logInfo(formatRes(ctx, resTime));
    }
};

//格式化响应日志
var formatRes = function (ctx, resTime) {
    var logText = new String();

    //响应日志开始
    logText += "\n" + "*************** response log start ***************" + "\n";

    //添加请求日志
    logText += formatReqLog(ctx.request, resTime);

    //响应状态码
    logText += "response status: " + ctx.status + "\n";

    //响应内容 因为返回报文可能比较多，所以暂时不用在日志里反应了 20180109
    // //因为有base64不便于看日志信息，所以私人定制一下
    // if (ctx.request.originalUrl.indexOf('/query_avatar') >= 0
    //     || ctx.request.originalUrl.indexOf('/query_feature') >= 0) {
    //     logText += "response body: " + "\n";
    // } else {
    //     logText += "response body: " + "\n" + JSON.stringify(ctx.body) + "\n";
    // }

    //响应日志结束
    logText += "*************** response log end ***************" + "\n";

    return logText;

}

//格式化错误日志
var formatError = function (ctx, err, resTime) {
    var logText = new String();

    //错误信息开始
    logText += "\n" + "*************** error log start ***************" + "\n";

    //添加请求日志
    logText += formatReqLog(ctx.request, resTime);

    //错误代码（自定义）
    logText += "err code: " + JSON.stringify(err.code) + "\n";
    //错误名称
    logText += "err name: " + err.name + "\n";
    //错误信息
    logText += "err message: " + err.message + "\n";
    //错误详情
    logText += "err stack: " + err.stack + "\n";

    //错误信息结束
    logText += "*************** error log end ***************" + "\n";

    return logText;
};

//格式化请求日志
var formatReqLog = function (req, resTime) {

    var logText = new String();

    var method = req.method;
    //访问方法
    logText += "request method: " + method + "\n";

    //请求原始地址
    logText += "request originalUrl:  " + req.originalUrl + "\n";

    //客户端ip
    logText += "request client ip:  " + req.ip + "\n";

    //请求参数
    if (method === 'GET') {
        logText += "request query:  " + JSON.stringify(req.query) + "\n";
    } else {
        //因为有base64不便于看日志信息，所以私人定制一下
        if (req.originalUrl.indexOf('api/user/recognize') >= 0 || req.originalUrl.indexOf('/captureinfo') >= 0) {
            logText += "request body: " + "\n";
        } else {
            logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
        }
    }
    //服务器响应时间
    logText += "response time: " + resTime + "\n";

    return logText;
}

module.exports = logUtil;
